import {defineStore} from 'pinia'
import {ref} from 'vue'
import {getServerWsUrl} from "~/.env-config.js";


export const useWebSocketStore = defineStore('websocket', () => {
    // const { appContext } = getCurrentInstance()
    const ws = ref(null)
    const isConnecting = ref(false)
    const reconnectAttempts = ref(0)
    const isLinked = ref(false)

    const reconnectDelay = 3000 // 每次重连前等待的时间（毫秒）
    const url = getServerWsUrl(import.meta.env)

    setInterval(() => {
        send({action: "ping"})
    }, 5000)


    function connect() {
        if (isConnecting.value) return

        isConnecting.value = true
        console.log('Attempting to connect WebSocket...')

        try {
            ws.value = new WebSocket(url)

            ws.value.onopen = () => {
                console.log('WebSocket 连接成功')
                isConnecting.value = false
                reconnectAttempts.value = 0
            }

            ws.value.onerror = (error) => {
                console.error('WebSocket error:', error)
                // 在错误发生时也尝试重连
                handleDisconnect()
            }

            ws.value.onclose = (event) => {
                console.log('WebSocket disconnected. Code:', event.code, 'Reason:', event.reason)
                handleDisconnect()
            }

            function handleDisconnect() {
                isConnecting.value = false
                console.log(`Attempting to reconnect... (${reconnectAttempts.value + 1})`)
                setTimeout(() => {
                    reconnectAttempts.value++
                    connect()
                }, reconnectDelay)
            }

        } catch (error) {
            console.error('Error creating WebSocket connection:', error)
            isConnecting.value = false
            // 如果创建WebSocket对象失败，立即尝试重连
            handleDisconnect()
        }
    }

    function send(message) {
        if (ws.value && ws.value.readyState === WebSocket.OPEN) {
            ws.value.send(typeof message === 'string' ? message : JSON.stringify(message))
        } else {
            console.error('WebSocket is not connected. Message not sent:', message)
        }
    }

    function close() {
        if (ws.value) {
            ws.value.close()
            ws.value = null // 确保 WebSocket 对象被正确清除
        }
    }

    return {
        ws,
        isConnecting,
        reconnectAttempts,
        connect,
        send,
        close,
        isLinked
    }
})